﻿using System;
using System.Net;
using log4net;

namespace NormalGsearch
{
    class GoogleAuthenticationProxy
    {
        private NormalGSearchViewModel viewModel;
        private string secureId;
        private ILog logger;

        public GoogleAuthenticationProxy(NormalGSearchViewModel viewModel)
        {
            this.viewModel = viewModel;
            logger = LogManager.GetLogger(typeof(GoogleAuthenticationProxy));            
        }

        public bool Authenticate()
        {
            bool success = false;

            secureId = "";

            try
            {
                using (var client = new WebClient())
                {
                    string response = client.DownloadString(string.Format("https://www.google.com/accounts/ClientLogin?accountType=GOOGLE&Email={0}&Passwd={1}&service=trendspro&source=test-test-v1", viewModel.Username, viewModel.Password));
                    string[] responseLines = response.Split('\n');

                    if (responseLines.Length >= 2)
                    {
                        // secure id is first line in response
                        secureId = responseLines[2];
                        success = true;
                        logger.Error("... authentication succeeded.");
                    }
                    else
                    {
                        logger.Error("... authentication failed due to invalid response!" );
                    }
                }
            }
            catch (Exception ex)
            {
                viewModel.StatusMessage = "Anmeldung bei Google mit Benutzername/Passwort fehlgeschlagen!";
                logger.Error("... authentication failed: " + ex);
            }

            return success;
        }

        public string SecureId
        {
            get { return secureId; }
        }
    }
}
